package com.cays.myresearch.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ScrollView;
import android.widget.Toast;

import com.cays.myresearch.R;
import com.cays.myresearch.Util.HttpUtil;
import com.cays.myresearch.action.LoginAction;
import com.cays.myresearch.adapter.QuestionAdapter;
import com.cays.myresearch.constant.Constant;
import com.cays.myresearch.entity.Question;
import com.cays.myresearch.ui.HeadControlPanel;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import in.srain.cube.views.ptr.PtrClassicDefaultHeader;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MultipartBody;
import okhttp3.Response;

public class QuestionActivity extends AppCompatActivity implements
        QuestionAdapter.QuestionItemClickListener,HeadControlPanel.HeadPanelCallback{
    private List<Question> questions=new ArrayList<Question>();
    private PtrFrameLayout ptrFrameLayout;
    private HeadControlPanel headControlPanel;
    private QuestionAdapter questionAdapter;
    private RecyclerView recyclerView;
    private boolean myQuestion=false,myAnswerQuestion=false,oftenQuestion=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myQuestion=getIntent().getBooleanExtra("my_question",false);
        myAnswerQuestion=getIntent().getBooleanExtra("my_answer_question",false);
        oftenQuestion=getIntent().getBooleanExtra("often_question",false);
        setContentView(R.layout.activity_question);
        if (getSupportActionBar() != null){
            getSupportActionBar().hide();
        }
        recyclerView=(RecyclerView)findViewById(R.id.question_list);
        ptrFrameLayout=(PtrFrameLayout)findViewById(R.id.question_refresh);
        initQuestion();
        initFresh();
    }
    //初始化界面问题
    private void initQuestion(){
        headControlPanel=(HeadControlPanel)findViewById(R.id.question_head_layout);
        headControlPanel.initHeadPanel();
        headControlPanel.setLeftImage(R.drawable.ic_back);
        if (myQuestion){
            headControlPanel.setMiddleTitle("我的问题");
            headControlPanel.setRightTitle("");
        }else if (myAnswerQuestion){
            headControlPanel.setMiddleTitle("我回答的问题");
            headControlPanel.setRightTitle("");
        }else {
            headControlPanel.setMiddleTitle("问题列表");
            headControlPanel.setRightTitle("发布问题");
        }
        headControlPanel.setHeadPanelCallback(this);
        questions.clear();
        GridLayoutManager gridLayoutManager=new GridLayoutManager(getApplicationContext(),1);
        recyclerView.setLayoutManager(gridLayoutManager);
        questionAdapter=new QuestionAdapter(questions);
        recyclerView.setAdapter(questionAdapter);questionAdapter.setItemClickListener(this);
    }
    public void initFresh(){
        //这里是一个自定义的头部刷新布局,自带的也有一个布局   new PtrDefaultHandler();
        PtrClassicDefaultHeader header = new PtrClassicDefaultHeader(this);
        ptrFrameLayout.addPtrUIHandler(header);
        //不仅仅是添加头布局,还需要设置到控件中 注:特别重要,不然没显示
        ptrFrameLayout.setHeaderView(header);
        ptrFrameLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                //执行调用下拉刷新监听
                ptrFrameLayout.autoRefresh(true);
            }
        },200);
        //设置下拉刷新监听
        ptrFrameLayout.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                // 默认实现，根据实际情况做改动
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                //在这里写自己下拉刷新数据的请求
                //需要结束刷新头
                refreshQuestion();
            }
        });
    }
    Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if(msg.what==1){
                String s=(String)msg.obj,info="",questionStr="";
                questions.clear();
                if(s.contains("~")){
                    questionStr=s.split("~")[1];
                    List<Question> questionList=Constant.gson.fromJson(questionStr,
                            new TypeToken<List<Question>>(){}.getType());
                    questions.addAll(questionList);
                }
            }else if (msg.what==0){
                questions.clear();
            }
            questionAdapter.notifyDataSetChanged();
            ptrFrameLayout.refreshComplete();
            return true;
        }
    });
    //下拉刷新事件
    private void refreshQuestion(){
        final String url;
        if (myQuestion){
            LoginAction action=new LoginAction();
            if (!action.hasUserInfo(getApplicationContext())){
                Toast.makeText(this,"未登录",Toast.LENGTH_SHORT).show();
                questionAdapter.notifyDataSetChanged();
                ptrFrameLayout.refreshComplete();
                return;
            }
            url=Constant.URL + "question/my_question";
            final MultipartBody.Builder builder=new MultipartBody.Builder();
            builder.setType(MultipartBody.FORM);
            builder.addFormDataPart("name",action.getName(getApplicationContext()));
            HttpUtil.sendHttpRequest(url,builder,handler,1,0);
        }else if (myAnswerQuestion){
            LoginAction action=new LoginAction();
            if (!action.hasUserInfo(getApplicationContext())){
                Toast.makeText(this,"未登录",Toast.LENGTH_SHORT).show();
                questionAdapter.notifyDataSetChanged();
                ptrFrameLayout.refreshComplete();
                return;
            }
            url=Constant.URL + "question/my_answer_question";
            final MultipartBody.Builder builder=new MultipartBody.Builder();
            builder.setType(MultipartBody.FORM);
            builder.addFormDataPart("name",action.getName(getApplicationContext()));
            HttpUtil.sendHttpRequest(url,builder,handler,1,0);
        }else if (oftenQuestion){
            url = Constant.URL + "question/often_question";
            HttpUtil.sendHttpRequest(url,handler,1,0);
        }else{
            url = Constant.URL + "question/list";
            HttpUtil.sendHttpRequest(url,handler,1,0);
        }

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
    //当问题点击时
    @Override
    public void questionItemClick(List<Question> questions,int position) {
        Question question=questions.get(position);
        String q= Constant.gson.toJson(question);
        Intent intent=new Intent(QuestionActivity.this,QuestionInfoActivity.class);
        intent.putExtra("intent_question",q);
        startActivity(intent);
    }
    //head点击事件
    @Override
    public void onHeadPanelClick(int itemId) {
        switch (itemId){
            case Constant.btn_left_title:finish();break;
            case Constant.btn_right_title:
                Intent intent=new Intent(this,PostQuestionActivity.class);
                startActivity(intent);break;
            default:break;
        }
    }
}
